package com.three.crm.page.procure;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.luck.picture.lib.style.BottomNavBarStyle;
import com.luck.picture.lib.style.PictureSelectorStyle;
import com.luck.picture.lib.style.SelectMainStyle;
import com.luck.picture.lib.style.TitleBarStyle;
import com.luck.picture.lib.utils.DensityUtil;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.tencent.cos.xml.transfer.TransferManager;
import com.tencent.cos.xml.transfer.TransferState;
import com.three.crm.R;
import com.three.crm.adapter.NinePictureAdapter;
import com.three.crm.base.BaseActivity;
import com.three.crm.bean.CompanyBean;
import com.three.crm.bean.CosTokenBean;
import com.three.crm.bean.FileBean;
import com.three.crm.bean.PoundBean;
import com.three.crm.constant.AppConstant;
import com.three.crm.http.CommonResultCallBack;
import com.three.crm.page.company.CompanyActivity;
import com.three.crm.page.visit.VisitEditActivity;
import com.three.crm.require.AppRequireService;
import com.three.crm.tencentcloud.BaseConfig;
import com.three.crm.tencentcloud.CosServiceFactory;
import com.three.crm.tencentcloud.CosServiceUtils;
import com.three.crm.util.AppManager;
import com.three.crm.util.GlideEngine;
import com.three.crm.util.GsonUtils;
import com.three.crm.util.SignUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 磅单上传
 * created by lqd on 2024-01-05.
 */
public class PoundEditActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks{

    private static final int REQUEST_GET_COS_TOKEN = 210;
    private static final int REQUEST_SUBMIT = 211;
    private static final int UPLOAD_COVER_PROGRESS = 220;
    private static final int UPLOAD_COVER_STATE = 221;
    private static final int UPLOAD_COVER_SUCCESS = 222;
    private static final int UPLOAD_COVER_FAIL = 223;

    private static final int REQUEST_COMPANY = 260;

    private static final String TEMP_IMG_PATH = "temp_img_path";

    public static final int RC_PERMISSES = 10; // requestCode
    public final static String[] PERMISSES = {Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE};
    private boolean hasPermiss = false;
    private TextView tvTitle,tvCustomer;
    private EditText etRemark;
    private PictureSelectorStyle selectorStyle;
    private BasePopupView popupView;

    private RecyclerView rvPicture;
    private NinePictureAdapter ninePictureAdapter;
    private int maxSelectPicture = 9;
    private List<FileBean> pictureList = new ArrayList<>();

    private TransferManager transferManager;
    private CosServiceUtils serviceUtils;

    private int companyId = 0;
    private int detailId = 0;
    private PoundBean bean;

    private ActivityResultLauncher<Intent> intentActivityResultLauncher;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData();
            switch (msg.what){
                case UPLOAD_COVER_PROGRESS:
                    long completeCover = bundle.getLong("complete");
                    long targetCover = bundle.getLong("target");
                    // setDialogLoading("正在上传问题照片：" + getPercent(completeCover,targetCover) + "%");
                    break;
                case UPLOAD_COVER_STATE:
                    hideDialog();
                    break;
                case UPLOAD_COVER_SUCCESS:
                    String tempUrl = bundle.getString(TEMP_IMG_PATH);
                    Log.i("TAG","tempUrl="+tempUrl);
                    handleImg(tempUrl);
                    break;
                case UPLOAD_COVER_FAIL:
                    hideDialog();
                    showToast("上传问题照片失败");
                    break;

            }
        }
    };

    private void handleImg(String tempUrl) {
        FileBean bean = new FileBean();
        bean.setUrl(tempUrl);
        pictureList.add(bean);
        ninePictureAdapter.setNewData(pictureList);
    }

    @Override
    protected void initParms(Bundle bundle) {
        if (bundle != null) {
            bean = bundle.getParcelable(AppConstant.EXTRAS_DATA);
        }
    }

    @Override
    protected int bindLayout() {
        return R.layout.activity_pound_edit;
    }

    @Override
    protected void initViews(View view, Bundle savedInstanceState) {
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == RESULT_OK) {
                    CompanyBean companyBean = (CompanyBean) result.getData().getExtras().get(AppConstant.EXTRAS_BEAN);
                    tvCustomer.setText(companyBean.getTitle());
                    companyId = companyBean.getId();
                }
            }
        });
        onCheckPermission();
        tvTitle = $(R.id.tv_title);
        tvTitle.setText(R.string.pound_edit);
        tvCustomer = $(R.id.tv_customer);
        etRemark = $(R.id.et_remark);

        rvPicture = $(R.id.rv_picture);
        GridLayoutManager layoutManager = new GridLayoutManager(this,3);
        rvPicture.setLayoutManager(layoutManager);
        ninePictureAdapter = new NinePictureAdapter();
        ninePictureAdapter.setType("");
        rvPicture.setAdapter(ninePictureAdapter);

        if (bean != null) {
            tvCustomer.setText(bean.getTitle());
            companyId = bean.getCompany_id();
            detailId = bean.getId();
            etRemark.setText(bean.getNote());
            String[] imgs = bean.getImgs_arr();
            if (imgs != null && imgs.length > 0) {
                for (int i = 0; i < imgs.length; i++) {
                    String url = imgs[i];
                    FileBean bean = new FileBean();
                    bean.setUrl(url);
                    pictureList.add(bean);
                }
                ninePictureAdapter.setNewData(pictureList);
            }
        }
    }

    private void onCheckPermission() {
        if (EasyPermissions.hasPermissions(this,PERMISSES)){
            hasPermiss = true;
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.app_name) + "需要使用相机、手机存储等权限，您是否同意?",
                    RC_PERMISSES, PERMISSES);
        }
    }

    @Override
    protected void setListener() {
        $(R.id.iv_left).setOnClickListener(this);
        $(R.id.btn_submit).setOnClickListener(this);
        $(R.id.ll_customer).setOnClickListener(this);
        $(R.id.iv_take_picture).setOnClickListener(this);
        ninePictureAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                FileBean bean = (FileBean) baseQuickAdapter.getItem(position);
                String imgUrl = bean.getUrl();
                switch (view.getId()){
                    case R.id.iv_delete:
                        deleteByPath(imgUrl);
                        break;
                }
            }
        });
    }

    private void deleteByPath(String path){
        int selectPos = -1;
        for (int i = 0; i < pictureList.size(); i++) {
            FileBean bean = pictureList.get(i);
            if (path == bean.getUrl()) {
                selectPos = i;
                break;
            }
        }
        pictureList.remove(selectPos);
        ninePictureAdapter.setNewData(pictureList);
    }

    @Override
    protected void widgetClick(View v) {
        switch (v.getId()){
            case R.id.iv_left:
                finish();
                break;
            case R.id.iv_take_picture:
                if (hasPermiss) {
                    if (pictureList.size() == maxSelectPicture) {
                        showToast("最多只能上传9张图片");
                    } else {
                        onTakePicture();
                    }
                } else {
                    onCheckPermission();
                }
                break;
            case R.id.btn_submit:
                onSubmit();
                break;
            case R.id.ll_customer:
                onSelectCompany();
                break;
        }
    }

    private void onSelectCompany() {
        Intent intent = new Intent(this, CompanyActivity.class);
        intentActivityResultLauncher.launch(intent);
    }

    private void onSubmit() {
        if (companyId == 0) {
            showToast("请选择客户");
            return;
        }
        if (pictureList.size() == 0) {
            showToast("请上传磅单照片");
            return;
        }
        String remark = etRemark.getText().toString().trim();
        if (TextUtils.isEmpty(remark)) {
            showToast("请填写备注说明");
            etRemark.requestFocus();
            return;
        }
        popupView = new XPopup.Builder(this)
                .asLoading("正在提交...").show();
        JSONObject jsonObject = new JSONObject();

        String files = "";
        int fileSize = pictureList.size();
        if (fileSize > 0) {
            for (int i = 0; i < fileSize; i++) {
                FileBean bean = pictureList.get(i);
                files += bean.getUrl();
                if (fileSize - 1 != i) {
                    files += ",";
                }
            }
        }

        try {
            jsonObject.put("userToken", AppManager.getToken());
            jsonObject.put("company_id",companyId);
            jsonObject.put("note",remark);
            jsonObject.put("id",detailId);
            jsonObject.put("images",files);
            jsonObject.put("timestamp",getTimestamp());
            String sign = SignUtil.genSign(jsonObject);
            jsonObject.put("sign",sign);
            Log.i("TAG","jsonObject="+jsonObject.toString());
            AppRequireService.poundEdit(this,REQUEST_SUBMIT,jsonObject,callBack);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void onTakePicture() {
        PictureSelector.create(this)
                .openGallery(SelectMimeType.ofImage())
                .setMaxSelectNum(maxSelectPicture - pictureList.size())
                .setSelectorUIStyle(selectorStyle)
                .setSelectionMode(SelectModeConfig.MULTIPLE)
                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        handlePictureList(result);
                    }

                    @Override
                    public void onCancel() {
                        showToast("您取消了选择");
                    }
                });
    }

    private void handlePictureList(ArrayList<LocalMedia> result) {
        for (int i = 0; i < result.size(); i++) {
            LocalMedia localMedia = result.get(i);
            onUploadImg(localMedia);
        }
    }

    private void onUploadImg(LocalMedia localMedia) {
        popupView = new XPopup.Builder(this)
                .asLoading("正在上传...").show();
        serviceUtils.uploadFile(this, localMedia.getRealPath(), localMedia.getFileName(), localMedia.getMimeType(), new CosServiceUtils.UpLoadCallBack() {
            @Override
            public void onProgress(long complete, long target) {
                Message message = new Message();
                message.what = UPLOAD_COVER_PROGRESS;
                Bundle bundle = new Bundle();
                bundle.putLong("complete",complete);
                bundle.putLong("target",target);
                message.setData(bundle);
                handler.sendMessage(message);
            }

            @Override
            public void onStatusChange(TransferState state) {
                //Log.i(TAG,"11state="+state);
                if (state == TransferState.COMPLETED) {
                    Message message = new Message();
                    message.what = UPLOAD_COVER_STATE;
                    handler.sendMessage(message);
                }
            }

            @Override
            public void onSuccess(String url) {
                //Log.i(TAG,"11onSuccessUrl="+url);
                Message message = new Message();
                message.what = UPLOAD_COVER_SUCCESS;
                Bundle bundle = new Bundle();
                bundle.putString(TEMP_IMG_PATH,url);
                message.setData(bundle);
                handler.sendMessage(message);
            }

            @Override
            public void onFail() {
                //Log.i(TAG,"onFail");
                Message message = new Message();
                message.what = UPLOAD_COVER_FAIL;
                handler.sendMessage(message);
            }
        });
    }

    @Override
    protected void initData(Context mContext) {
        popupView = new XPopup.Builder(this)
                .asLoading("正在获取...");
        setWechatStyle(mContext);
        initCosToken();
        queryCompany();
    }

    private void queryCompany() {
//        popupView = new XPopup.Builder(this)
//                .asLoading("正在获取客户信息...").show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userToken", AppManager.getToken());
            jsonObject.put("pageNo",1);
            jsonObject.put("pageSize",100);
            jsonObject.put("keyword","");
            jsonObject.put("timestamp",getTimestamp());
            String sign = SignUtil.genSign(jsonObject);
            jsonObject.put("sign",sign);
            Log.i("TAG","jsonObject="+jsonObject.toString());
            AppRequireService.queryCompanyList(this,REQUEST_COMPANY,jsonObject,callBack);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void initCosToken() {
        popupView = new XPopup.Builder(this)
                .asLoading("正在获取授权信息...").show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userToken", AppManager.getToken());
            jsonObject.put("timestamp",getTimestamp());
            String sign = SignUtil.genSign(jsonObject);
            jsonObject.put("sign",sign);
            Log.i("TAG","jsonObject="+jsonObject.toString());
            AppRequireService.getCosTokenData(this,REQUEST_GET_COS_TOKEN,jsonObject,callBack);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private CommonResultCallBack callBack = new CommonResultCallBack(this) {
        @Override
        public void onResult(String result, int requireCode) {
            Log.i("TAG","result="+result);
            hideDialog();
            if (requireCode == REQUEST_GET_COS_TOKEN) {
                if (result != null) {
                    CosTokenBean bean = GsonUtils.parseJsonWithGson(result, CosTokenBean.class);
                    initFileWithCosService(bean);
                }
            } else if (requireCode == REQUEST_COMPANY) {
                //AppManager.setNeedUpdate(true);
               // showToast("操作成功");
               // finish();
            } else if (requireCode == REQUEST_SUBMIT) {
                AppManager.setNeedUpdate(true);
                showToast("操作成功");
                finish();
            }
        }

        @Override
        public void onConnectTimeOut(Call call, Exception e, int requireCode) {
            showToast(e.getMessage());
            hideDialog();
        }

        @Override
        public void onFail(String msg, int requireCode) {
            showToast(msg);
            hideDialog();
        }
    };

    private void initFileWithCosService(CosTokenBean bean) {
        transferManager = CosServiceFactory.getTransferManager(this, BaseConfig.REGION,BaseConfig.SECRETID,BaseConfig.SECRETKEY,bean.getToken(),bean.getStartTime(),bean.getExpirationAt(),true);
        serviceUtils = new CosServiceUtils(transferManager);
    }

    private void hideDialog(){
        popupView.smartDismiss();
//        if (popupView != null) {
//            popupView.smartDismiss();
//        }
    }

    private void setWechatStyle(Context context) {
        selectorStyle = new PictureSelectorStyle();
        // 主体风格
        SelectMainStyle numberSelectMainStyle = new SelectMainStyle();
        numberSelectMainStyle.setSelectNumberStyle(true);
        numberSelectMainStyle.setPreviewSelectNumberStyle(false);
        numberSelectMainStyle.setPreviewDisplaySelectGallery(true);
        numberSelectMainStyle.setSelectBackground(R.drawable.ps_default_num_selector);
        numberSelectMainStyle.setPreviewSelectBackground(R.drawable.ps_preview_checkbox_selector);
        numberSelectMainStyle.setSelectNormalBackgroundResources(R.drawable.ps_select_complete_normal_bg);
        numberSelectMainStyle.setSelectNormalTextColor(ContextCompat.getColor(context, R.color.ps_color_53575e));
        numberSelectMainStyle.setSelectNormalText(getString(R.string.ps_send));
        numberSelectMainStyle.setAdapterPreviewGalleryBackgroundResource(R.drawable.ps_preview_gallery_bg);
        numberSelectMainStyle.setAdapterPreviewGalleryItemSize(DensityUtil.dip2px(context, 52));
        numberSelectMainStyle.setPreviewSelectText(getString(R.string.ps_select));
        numberSelectMainStyle.setPreviewSelectTextSize(14);
        numberSelectMainStyle.setPreviewSelectTextColor(ContextCompat.getColor(context, R.color.ps_color_white));
        numberSelectMainStyle.setPreviewSelectMarginRight(DensityUtil.dip2px(context, 6));
        numberSelectMainStyle.setSelectBackgroundResources(R.drawable.ps_select_complete_bg);
        numberSelectMainStyle.setSelectText(getString(R.string.ps_send_num));
        numberSelectMainStyle.setSelectTextColor(ContextCompat.getColor(context, R.color.ps_color_white));
        numberSelectMainStyle.setMainListBackgroundColor(ContextCompat.getColor(context, R.color.ps_color_black));
        numberSelectMainStyle.setCompleteSelectRelativeTop(true);
        numberSelectMainStyle.setPreviewSelectRelativeBottom(true);
        numberSelectMainStyle.setAdapterItemIncludeEdge(false);

        // 头部TitleBar 风格
        TitleBarStyle numberTitleBarStyle = new TitleBarStyle();
        numberTitleBarStyle.setHideCancelButton(true);
        numberTitleBarStyle.setAlbumTitleRelativeLeft(true);
        numberTitleBarStyle.setTitleAlbumBackgroundResource(R.drawable.ps_album_bg);
        numberTitleBarStyle.setTitleDrawableRightResource(R.drawable.ps_ic_grey_arrow);
        numberTitleBarStyle.setPreviewTitleLeftBackResource(R.drawable.ps_ic_normal_back);

        // 底部NavBar 风格
        BottomNavBarStyle numberBottomNavBarStyle = new BottomNavBarStyle();
        numberBottomNavBarStyle.setBottomPreviewNarBarBackgroundColor(ContextCompat.getColor(context, R.color.ps_color_half_grey));
        numberBottomNavBarStyle.setBottomPreviewNormalText(getString(R.string.ps_preview));
        numberBottomNavBarStyle.setBottomPreviewNormalTextColor(ContextCompat.getColor(context, R.color.ps_color_9b));
        numberBottomNavBarStyle.setBottomPreviewNormalTextSize(16);
        numberBottomNavBarStyle.setCompleteCountTips(false);
        numberBottomNavBarStyle.setBottomPreviewSelectText(getString(R.string.ps_preview_num));
        numberBottomNavBarStyle.setBottomPreviewSelectTextColor(ContextCompat.getColor(context, R.color.ps_color_white));

        selectorStyle.setTitleBarStyle(numberTitleBarStyle);
        selectorStyle.setBottomBarStyle(numberBottomNavBarStyle);
        selectorStyle.setSelectMainStyle(numberSelectMainStyle);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults,this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        hasPermiss = true;
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onRationaleAccepted(int requestCode) {

    }

    @Override
    public void onRationaleDenied(int requestCode) {

    }
}